package biz

import (
	"context"
	"errors"
	log "github.com/sirupsen/logrus"
	"strings"
	"time"
)

// EmailCtxRepo 邮件repo接口
type EmailCtxRepo interface {
	// SaveCtx 保存邮箱名
	SaveCtx(ctx context.Context, email string) error
}

// EmailCtxUseCase 邮件用例
type EmailCtxUseCase struct {
	cache     Cache
	emailRepo EmailCtxRepo
}

func NewEmailCtxUseCase(cache Cache, emailRepo EmailCtxRepo) *EmailCtxUseCase {
	return &EmailCtxUseCase{cache: cache, emailRepo: emailRepo}
}

func (ec *EmailCtxUseCase) SaveEmail(email string) error {
	if email == "" || !strings.Contains(email, "@") || !strings.Contains(email, ".com") {
		return errors.New("bad email")
	}
	ctx := context.Background()
	if err := ec.cache.SetRateNumberInLimitTime(ctx, email, 1, 1*time.Second); err != nil {
		return errors.New("bad rate limit")
	}
	if err := ec.emailRepo.SaveCtx(ctx, email); err != nil {
		log.Errorf("EmailCtxUseCase#SaveCtx err:%v", err)
		return err
	}
	return nil
}
